package com.party.web.web.controller.gatherForm;

import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.PinyinUtil;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherFormInfo;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormOptionService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.member.IMemberGroupService;
import com.party.notify.notifyPush.servce.INotifySendService;
import com.party.web.biz.file.ExcelExportService;
import com.party.web.biz.gatherForm.GatherFormInfoBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("gatherForm/form")
public class GatherFormController {

	@Autowired
	private IGatherFormService gatherFormService;
	@Autowired
	private IGatherFormInfoService gatherFormInfoService;
	@Autowired
	private IGatherProjectService gatherProjectService;
	@Autowired
	private IGatherFormOptionService gatherFormOptionService;
	@Autowired
	private IMemberGroupService memberGroupService;
	@Autowired
	private GatherFormInfoBizService gatherFormInfoBizService;
	@Autowired
    private ExcelExportService excelExportService;
	@Autowired
	private INotifySendService notifySendService;

    Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 表单收集信息列表
	 * 
	 * @param projectId
	 * @param commonInput
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@DataControl
	@RequestMapping("list")
	public ModelAndView list(@ControlParam(table = "gather_d_project", column = "create_by")String projectId, CommonInput commonInput, Page page) throws Exception {
		page.setLimit(30);
		Map<String, Object> params = CommonInput.appendParams(commonInput);
		params.put("projectId", projectId);
		List<Map<String, Object>> gatherForms = gatherFormInfoService.webListPage(params, page);

		/*List<GatherFormInfoOutput> outputs = Lists.newArrayList();
		List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
		for (Map<String, Object> input : gatherForms) {
			GatherFormInfoOutput output = new GatherFormInfoOutput();
			String maxIndex = input.get("maxIndex") != null ? input.get("maxIndex").toString() : "";
			output.setMaxIndex(maxIndex);
			String fieldValue = input.get("fieldValue") != null ? input.get("fieldValue").toString() : "";
			String [] result = new String[fields.size()];
			for (int i = 0; i < fieldValue.split("maxIndex").length; i++) {
				result[i] = fieldValue.split("maxIndex")[i];
			}
			output.setFieldValues(result);
			if (null != input.get("createBy") && StringUtils.isNotEmpty(input.get("createBy").toString())) {
				Member member = memberService.get(input.get("createBy").toString());
				output.setMember(member);
			}
			output.setCreateDate((Date) input.get("createDate"));
			outputs.add(output);
		}*/
		ModelAndView mv = new ModelAndView("gatherForm/formInfoList");
		mv.addObject("input", commonInput);
		mv.addObject("page", page);

		List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
		mv.addObject("fields", fields);

		mv.addObject("formInfos", gatherForms);
		GatherProject gatherProject = gatherProjectService.get(projectId);
		mv.addObject("project", gatherProject);
		return mv;
	}

	/**
	 * 表单信息详情
	 * 
	 * @param maxIndex
	 * @param projectId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/formInfo")
	public ModelAndView formInfo(String maxIndex, String projectId) {
		ModelAndView mv = new ModelAndView("gatherForm/formInfo");
		List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));

		//查询来源字段
		String resourceId = null;
		for (GatherForm gf : fields){
			if (gf.getCategory().equals(Constant.FIELD_RESOURCE)){
				resourceId = gf.getId();
			}
		}

		mv.addObject("fields", fields);

		GatherFormInfo t = new GatherFormInfo();
		t.setProjectId(projectId);
		t.setMaxIndex(Integer.valueOf(maxIndex));
		List<GatherFormInfo> infos = gatherFormInfoService.list(t);

		//特殊处理来源
		if (null != resourceId){
			for (GatherFormInfo gi :  infos){
				if (gi.getFieldId().equals(resourceId)){
					MemberGroup member = memberGroupService.get(gi.getFieldValue());
					if (null != member){
						gi.setFieldValue(member.getRealname());
					}
				}
			}
		}
		mv.addObject("infos", infos);
		return mv;
	}

	/**
	 * 删除表单字段
	 * 
	 * @param projectId
	 * @param maxIndex
	 * @return
	 */
	@ResponseBody
	@RequestMapping("delete")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult delete(String projectId, String maxIndex) {
		try {
			if (StringUtils.isEmpty(projectId) || StringUtils.isEmpty(maxIndex)) {
				AjaxResult ajaxResult = new AjaxResult();
				ajaxResult.setSuccess(false);
				return ajaxResult;
			}
			gatherFormInfoService.deleteByProjectId(projectId, maxIndex);

			GatherProject gatherProject = gatherProjectService.get(projectId);
			gatherProject.setQuantity(gatherProject.getQuantity() - 1);
			gatherProjectService.update(gatherProject);
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("删除数据异常", e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("删除数据异常");
		}
	}
	
	/**
	 * 删除单个字段
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("deleteField")
	public AjaxResult deleteField(String id){
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
		gatherFormService.delete(id);
		return AjaxResult.success();
	}
	
	/**
	 * 删除单个选项
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("deleteOption")
	public AjaxResult deleteOption(String id){
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
		gatherFormOptionService.delete(id);
		return AjaxResult.success();
	}

	/**
	 * 导出表单收集信息
	 *
	 * @param projectId
	 * @param commonInput
	 * @return
	 * @throws IOException
	 */
	@DataControl
	@ResponseBody
	@RequestMapping("exportFormInfo")
	public AjaxResult exportFormInfo(@ControlParam(table = "gather_d_project", column = "create_by") String projectId, CommonInput commonInput) {
		try {
			String fileName = "表单收集.xlsx";
			GatherProject gatherProject = gatherProjectService.get(projectId);
			Map<String, Object> params = CommonInput.appendParams(commonInput);
			params.put("projectId", projectId);
			List<Map<String, Object>> gatherForms = gatherFormInfoService.webListPage(params, null);
			List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
			SXSSFWorkbook workbook = gatherFormInfoBizService.exportExcel(gatherForms, fields, gatherProject.getShowResource());
			String allPath = excelExportService.getExcelPath(fileName, "gatherForm", new ExportExcel(), workbook);
			return AjaxResult.success((Object) allPath);
		} catch (Exception e) {
			logger.error("表单信息导出异常", e);
		}
		return AjaxResult.error("导出异常");
	}

	/**
	 * 填写表单
	 *
	 * @param project 项目数据
	 * @param result
	 * @return
	 */
	@ResponseBody
	@RequestMapping("save")
	public AjaxResult save(GatherProject project, BindingResult result) {
		// 数据验证
		if (result.hasErrors()) {
			List<ObjectError> allErrors = result.getAllErrors();
			String description = allErrors.get(0).getDefaultMessage();
			return AjaxResult.error(description);
		}

		Integer maxIndex = gatherFormInfoService.getMaxIndex(project.getId());

		if (StringUtils.isEmpty(project.getId())) {
			return AjaxResult.error("项目id不能为空");
		}

		String currentId = null;
		MemberGroup currentUser = RealmUtils.getCurrentUser();
		if (currentUser != null) {
			currentId = currentUser.getId();
		}

		if (null != project.getInfoItems()) {
			for (GatherFormInfo info : project.getInfoItems()) {
				if (StringUtils.isEmpty(info.getFieldValue())) {
					info.setFieldValue(" ");
				} else {
					info.setFieldValue(PinyinUtil.filterEmoji(info.getFieldValue(), ""));
				}
				if (StringUtils.isEmpty(info.getId())) {
					info.setMaxIndex(null == maxIndex ? 1 : maxIndex + 1);
					info.setProjectId(project.getId());
					info.setCreateBy(currentId);
					info.setUpdateBy(currentId);
					gatherFormInfoService.insert(info);
				}
			}
		}

		GatherProject dbProject = gatherProjectService.get(project.getId());
		dbProject.setQuantity(dbProject.getQuantity() + 1L);
		gatherProjectService.update(dbProject);

		if (StringUtils.isNotEmpty(dbProject.getIsRemindMe()) && Integer.valueOf(dbProject.getIsRemindMe()).equals(YesNoStatus.YES.getCode())) {
			if (StringUtils.isNotEmpty(dbProject.getPhone())) {
				notifySendService.sendSuccessForm(dbProject.getPhone(), dbProject);
			} else {
				MemberGroup member = memberGroupService.get(dbProject.getCreateBy());
				notifySendService.sendSuccessForm(member.getMobile(), dbProject);
			}
		}
		return AjaxResult.success();
	}

	/**
	 * @param projectId 项目id
	 * @param targetId  报名id
	 * @param isNew     是否第一次 第一次就加载表单所有字段
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getFormInfoByTargetId")
	public AjaxResult getFormInfoByTargetId(String projectId, String targetId, boolean isNew) {
		if (StringUtils.isEmpty(targetId) || StringUtils.isEmpty(projectId)) {
			return AjaxResult.error("项目id或者业务id不能为空");
		}
		try {
			Map<String, Object> result = Maps.newHashMap();
			if (isNew) {
				List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
				result.put("fields", fields);
			}
			GatherFormInfo t = new GatherFormInfo();
			t.setProjectId(projectId);
			t.setTargetId(targetId);
			List<GatherFormInfo> infos = gatherFormInfoService.list(t);
			result.put("infos", infos);
			return AjaxResult.success(result);
		} catch (Exception e) {
			logger.error("获取业务id对应的数据异常", e);
			return AjaxResult.error("获取数据异常");
		}
	}
}
